<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="公司名稱" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入公司名稱"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="案件名稱" prop="caseName">
        <el-input
          v-model="queryParams.caseName"
          placeholder="请输入案件名稱"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="文件號" prop="fileNumber">
        <el-input
          v-model="queryParams.fileNumber"
          placeholder="请输入文件號"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="客戶經理" prop="customerManager">
        <el-input
          v-model="queryParams.customerManager"
          placeholder="请输入客戶經理"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="報價日期" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="開始日期"
          end-placeholder="結束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            v-hasPermi="['system:prodect:add']"
            @click="handleAdd"
            >编辑商品</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:prodect:update']"
            >修改</el-button
          >
        </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:offer:delete']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:offer:export']"
          >導出</el-button
        >
      </el-col>
      <el-col :span="1.5">
           <el-button 
          v-if="queryParams.seriesId"
              type="warning" 
              plain 
              icon="Close"
              @click="handleClose"
           >关闭</el-button>
        </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :border="true"
      :data="specificationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="文件號"
        :show-overflow-tooltip="true"
        width="120"
        prop="fileNumber"
      >
      </el-table-column>
      <el-table-column
        label="案件名稱"
        prop="caseName"
          width="80"
        :show-overflow-tooltip="true"
      >
      </el-table-column
      >
      <el-table-column
        label="公司名稱"
        :show-overflow-tooltip="true"
        prop="customerName"
      >
      </el-table-column>
      <el-table-column
        label="聯繫人"
        :show-overflow-tooltip="true"
        width="70"
        prop="name"
      >
      </el-table-column>
      <el-table-column
        label="負責業務"
        :show-overflow-tooltip="true"
          width="90"
        prop="customerManager"
      >
      </el-table-column>
      <!-- <el-table-column
        label="負責業務"
        :show-overflow-tooltip="true"
        width="90"
        prop="nickName"
      >
      </el-table-column> -->
      <!-- <el-table-column label="聯繫電話" :show-overflow-tooltip="true" width="90" prop="customerPhone" >
        </el-table-column> -->
   
      <!-- <el-table-column label="聯繫人地址" :show-overflow-tooltip="true"  prop="address" >
        </el-table-column> -->
      <!-- <el-table-column label="聯繫人電話" :show-overflow-tooltip="true" width="90"  prop="phone" >
        </el-table-column> -->

      <el-table-column
        label="報價日期"
        :show-overflow-tooltip="true"
        prop="offerDate"
      >
      </el-table-column>

      <el-table-column
        label="運費"
        :show-overflow-tooltip="true"
        width="60"
        prop="freight"
      >
      </el-table-column>

      <el-table-column
        label="支付方式"
        :show-overflow-tooltip="true"
        prop="payment"
      >
      </el-table-column>
      <el-table-column
        label="商品合計(折後)"
        :show-overflow-tooltip="true"
        width="80"
        prop="totalSelectedPrice"
      >
      </el-table-column>
      <el-table-column
        label="總金額"
        :show-overflow-tooltip="true"
        width="70"
        prop="totalAmount"
      >
      </el-table-column>
    <el-table-column
  label="報價單狀態"
  width="120"
  :show-overflow-tooltip="true"
  prop="quotedStates"
>
  <template #default="scope">
    <div style="display: flex; align-items: center; gap: 8px">
      <span v-if="scope.row.caseName">以案件狀態爲準</span>
      <span v-else>
        <el-tooltip
          v-if="scope.row.quotedStates === '未成交' && scope.row.remark"
          :content="'未成交原因: ' + scope.row.remark"
          placement="top"
          effect="light"
        >
          <span style="cursor: pointer; color: #f56c6c">{{ scope.row.quotedStates || '進行中' }}</span>
        </el-tooltip>
        <span v-else>{{ scope.row.quotedStates || '進行中' }}</span>
      </span>
      <el-tooltip content="報價單結案維護" placement="top">
        <el-button
          link
          v-if="!scope.row.caseName"
          type="primary"
          icon="CircleCheck"
          @click="handleMaintainStatus(scope.row)"
          v-hasPermi="['system:quoted:add']"
        ></el-button>
      </el-tooltip>
    </div>
  </template>
</el-table-column>
      <el-table-column
  label="案件成交状态"
    width="80"
  :show-overflow-tooltip="true"
  prop="bargain"
>
  <template #default="scope">
    <template v-if="scope.row.caseName">
          <el-tag
            :type="scope.row.schedule === '結案' ? 'success' : 'info'"
            size="small"
          >
            {{ scope.row.schedule === '結案' ? '已成交' : '进行中' }}
          </el-tag>
        </template>
  </template>
</el-table-column>
      <el-table-column label="最新報價" align="center"  prop="url">
        <template #default="scope">
  <span v-if="!scope.row.url" class="text-gray">无报价单</span>
  <a
    v-else
    href="#"
    class="text-link"
    @click.prevent="openExport(scope.row.url)"
    v-hasPermi="['system:offer:download']"
  >
    查看
  </a>
</template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="修改報價單" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:offer:update']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="歷史報價單" placement="top">
            <el-button
              link
              type="primary"
              icon="Clock"
              @click="handleselectOld(scope.row)"
              v-hasPermi="['system:offer:selectold']"
            ></el-button>
          </el-tooltip>

       
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />




    <el-drawer
    v-model="history"
    title="歷史報價單:"
    direction="rtl"
    size="50%"
  >
    <el-table :data="tableData">
      <el-table-column prop="createTime" align="center"  label="報價單生成日期"  />
      <el-table-column label="報價單" align="center" prop="url">
        <template #default="scope">
          <a
            href="#"
            class="text-link"
            @click.prevent="openExport(scope.row.url)"
            v-hasPermi="['system:offer:download']"
          >
            {{  scope.row.url }}
          </a>
        </template>
      </el-table-column>
              <el-table-column prop="version" align="center" label="版本" />
    </el-table>
  </el-drawer>
  </div>



  <!-- 在适当的位置添加这个模板 -->
  <el-dialog
    v-model="showUnfinishedDialog"
    title="未成交原因"
    width="500px"
    :before-close="handleDialogClose"
  >
    <el-select
      v-model="selectedReasons"
      multiple
      style="width: 100%"
      placeholder="請選擇未成交原因（可多選）"
    >
      <el-option-group
        v-for="(items, group) in unfinishedReasons"
        :key="group"
        :label="group"
      >
        <el-option
          v-for="item in items"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-option-group>
    </el-select>
    
    <el-input
      v-if="selectedReasons.includes('其他（備註填寫）')"
      v-model="otherRemark"
      type="textarea"
      rows="2"
      placeholder="請輸入其他原因"
      style="margin-top: 10px"
    />
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showUnfinishedDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmUnfinished">確定</el-button>
      </span>
    </template>
  </el-dialog>

</template>

    
   
   <script setup name="case">
import { getofferAndcase, addquotedStates, deloffer, getpdf, getofferAndcaseById } from "@/api/business/offrt.js";
import { 
  ElMessageBox, 
  ElButton, 
  ElSelect, 
  ElOption, 
  ElOptionGroup, 
  ElInput, 
  ElMessage 
} from 'element-plus';
import { ref, computed, h,createVNode } from 'vue';


const { proxy } = getCurrentInstance();

// 初始化格式化的选项数据
const specificationList = ref([]);
const history = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const specificationIds = ref([]);
const tableData = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const dateRange = ref([]);


const route = useRoute();

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    seriesId: route.params.Id,
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
function getList() {
  loading.value = true;
  if(queryParams.value.seriesId && queryParams.value.seriesId != null){

    getofferAndcaseById(queryParams.value.seriesId).then((response) => {
      // 处理响应数据，格式化 totalSelectedPrice 和 计算 totalAmount
      const formattedRows = response.rows.map((row) => ({
        ...row,
        totalSelectedPrice: Math.floor(Number(row.totalSelectedPrice)),
        totalAmount: Number(row.freight) + Number(row.totalSelectedPrice),
      }));
      specificationList.value = formattedRows;
      total.value = response.total;
      loading.value = false;
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
      loading.value = false;
    });
  }else{

  getofferAndcase(proxy.addDateRange(queryParams.value, dateRange.value))
    .then((response) => {
      // 处理响应数据，格式化 totalSelectedPrice 和 计算 totalAmount
      const formattedRows = response.rows.map((row) => ({
        ...row,
        totalSelectedPrice: Math.floor(Number(row.totalSelectedPrice)),
        totalAmount: Number(row.freight) + Number(row.totalSelectedPrice),
      }));
      specificationList.value = formattedRows;
      total.value = response.total;
      loading.value = false;
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
      loading.value = false;
    });
  }
}
const selectedReasons = ref([])
const otherRemark = ref('')
const currentRow = ref(null)
const showUnfinishedDialog = ref(false)

//未成交原因
const unfinishedReasons = {
  'A. 客戶方原因': [
    '需求不明確/變化',
    '預算不足/優先順序調整',
    '決策流程複雜（多人審批）',
    '關鍵人反對',
    '客戶內部架構變動'
  ],
  'B. 產品/服務原因': [
    '功能不符合需求',
    '價格高於預期',
    '缺少關鍵服務（如售後支援）',
    '定制化需求無法滿足'
  ],
  'C. 競品因素': [
    '競品價格更低',
    '競品功能更匹配',
    '客戶與競品有歷史合作',
    '競品提供額外條款（如賬期）'
  ],
  'D. 銷售過程問題': [
    '跟進不及時',
    '未識別關鍵決策人',
    '價值傳遞不清晰',
    '演示/方案不專業'
  ],
  'E. 其他': [
    '客戶主動放棄專案',
    '外部不可抗力（政策、經濟環境）',
    '其他（備註填寫）'
  ]
}

// 修改处理函数
// 处理未成交状态
const handleUnfinishedStatus = (row) => {
  currentRow.value = row
  selectedReasons.value = []
  otherRemark.value = ''
  showUnfinishedDialog.value = true
}

// 确认未成交原因
const handleConfirmUnfinished = () => {
  if (selectedReasons.value.length === 0) {
    ElMessage.warning('請至少選擇一個未成交原因')
    return
  }
  
  let finalReason = selectedReasons.value.join('、')
  if (selectedReasons.value.includes('其他（備註填寫）') && otherRemark.value) {
    finalReason += `；其他原因：${otherRemark.value}`
  }
  
  submitStatus(currentRow.value, '未成交', finalReason)
  showUnfinishedDialog.value = false
}

// 关闭对话框
const handleDialogClose = (done) => {
  selectedReasons.value = []
  otherRemark.value = ''
  if (done) done()
}

// 修改原来的 handleMaintainStatus 函数
const handleMaintainStatus = async (row) => {
  try {
    await ElMessageBox({
      title: '狀態維護',
      message: h('div', { style: 'text-align: center; margin: 20px 0;' }, [
        h(ElButton, {
          type: 'success',
          onClick: () => {
            ElMessageBox.close()
            submitStatus(row, '已成交')
          }
        }, { default: () => '已成交' }),
        ' ',
        h(ElButton, {
          type: 'warning',
          onClick: () => {
            ElMessageBox.close()
            handleUnfinishedStatus(row)
          }
        }, { default: () => '未成交' }),
        ' ',
        h(ElButton, {
          type: 'info',
          onClick: () => {
            ElMessageBox.close()
            submitStatus(row, '進行中')
          }
        }, { default: () => '進行中' })
      ]),
      showCancelButton: false,
      showConfirmButton: false,
    })
  } catch (error) {
    console.error('狀態維護操作失敗:', error)
  }
}
// 提交状态到后端
const submitStatus = async (row, status, reason = '') => {
  try {
    const params = {
      quotedId: row.id, // 报价单ID
      quotedStates: status,
      remark: reason // 未成交原因
    };
    
    // 调用后端接口
    await addquotedStates(params);
    proxy.$modal.msgSuccess("狀態更新成功");
    // 刷新列表
    getList();
  } catch (error) {
    proxy.$modal.msgError("狀態更新失敗");
    console.error('提交狀態失敗:', error);
  }
};

//打开弹窗查看历史
function handleselectOld(row) {
  history.value = true;
  console.log("row", row.id);
  getpdf(row.id).then(response => {
    tableData.value = response.rows;
  })
}

  // 返回按钮
  function handleClose() {
 const obj = { path: "/business/case/update/" + route.params.Id};
 proxy.$tab.closeOpenPage(obj);
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;

  proxy.$modal
    .confirm('是否确认删除为"' + id + '"的数据项?')
    .then(function () {
      return deloffer(id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/**
 * 下载按钮
 */
function openExport(url) {
  window.open(url);
}
/** 導出按钮操作 */
function handleExport() {
  proxy.download(
    "offer/export",
    {
      ...queryParams.value,
    },
    `报价单明细_${new Date().getTime()}.xlsx`
  );
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  specificationIds.value = selection.map((item) => item.specificationId);

  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
//跳转
const handleUpdate = (row) => {
  const baseUrl = "http://192.168.110.11:8087/cartlist";
  const fullUrl = `${baseUrl}?id=${row.id}&fromLink=true`;
  // window.location.href = fullUrl;  使用 window.location.href 进行跳转
  // 或者使用 window.open 打开新窗口
  window.open(fullUrl, "_blank");
};

function reset() {
  form.value = {};
  contacts.value = [{}];
  proxy.resetForm("addclientele");
}

getList();
</script>
  
  <style scoped>

:deep(.reason-select-container) {
  .el-select {
    width: 100%;
  }
  
  .el-select__tags {
    max-width: 100%;
  }
}

:deep(.el-message-box) {
  width: 500px;
  max-width: 95vw;
}
.linkman-input-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.linkman-input-group .el-input {
  flex: 1;
  margin-right: 10px;
}
.text-link {
  color: #409eff; /* 设置文字颜色为蓝色 */
  text-decoration: none; /* 去掉下划线 */
  cursor: pointer; /* 鼠标悬停时显示指针 */
}

.text-link:hover {
  text-decoration: underline; /* 鼠标悬停时显示下划线 */
}
</style>